package com.hyk.commonLib.common.utils;

import androidx.annotation.StringDef;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by 贺玉琨 on 2019/3/7 0007.
 */
public class HashUtils {
    @Retention(RetentionPolicy.SOURCE)
    @StringDef({ALGORITHM_TYPE_MD5, ALGORITHM_TYPE_SHA_512, ALGORITHM_TYPE_SHA_1})
    private @interface Algorithm {
    }

    public static final String ALGORITHM_TYPE_MD5 = "MD5";
    public static final String ALGORITHM_TYPE_SHA_512 = "SHA-512";
    public static final String ALGORITHM_TYPE_SHA_1 = "SHA-1";

    public static String MD5(String SourceString) {
        return doHash(SourceString, ALGORITHM_TYPE_MD5);
    }

    /**
     * SHA-512 加密
     */
    public static String sha512(String SourceString) {
        return doHash(SourceString, ALGORITHM_TYPE_SHA_512);
    }

    /**
     * SHA-1 加密
     */
    public static String sha1(String SourceString) {
        return doHash(SourceString, ALGORITHM_TYPE_SHA_1);
    }

    private static String doHash(String SourceString, @Algorithm String algorithm) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            md.update(SourceString.getBytes());
            byte[] resultBytes = md.digest();
            return EncodeUtils.toHexString(resultBytes).toLowerCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
}
